<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :visible.sync="dialog" title="用户注册" width="500px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="160px">
      <el-form-item label="账号" prop="busMainData.userAccount">
        <el-input v-model="form.busMainData.userAccount" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="姓名" prop="busMainData.userName">
        <el-input v-model="form.busMainData.userName" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="新密码" prop="busMainData.password">
        <el-input v-model="form.busMainData.password" type="password" auto-complete="on" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="busMainData.confirmPassword">
        <el-input v-model="form.busMainData.confirmPassword" type="password" auto-complete="on" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="手机" prop="busMainData.phone">
        <el-input v-model="form.busMainData.phone" style="width: 300px;"/>
      </el-form-item>
      <!-- <el-form-item label="手机验证码" prop="busMainData.smsVerifyCode">
        <el-input v-model="form.busMainData.smsVerifyCode" style="width: 300px;"/>
      </el-form-item>-->
      <el-form-item label="邮件" prop="busMainData.email">
        <el-input v-model="form.busMainData.email" style="width: 300px;"/>
      </el-form-item>
      <el-form-item label="所属公司">
        <el-autocomplete
          v-model="cpyName"
          :fetch-suggestions="cpySearchAsync"
          :trigger-on-focus="false"
          :highlight-first-item="true"
          value-key="cpyName"
          placeholder="请输入公司名称搜索"
          @select="handleCpySelect" />
      </el-form-item>
      <!-- <el-form-item label="所属公司">
        <el-select v-model="cpyCodes" style="width: 300px;" placeholder="请选择">
          <el-option
            v-for="(item, index) in cpyList"
            :key="item.cpyCode + index"
            :label="item.cpyName"
            :value="item.cpyCode"/>
        </el-select>
      </el-form-item>-->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">注册</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { userRegister } from '@/api/user'
import { getAllCpy } from '@/api/system/cpy'
import { isvalidPhone } from '@/utils/validate'
import md5 from 'js-md5'
export default {
  components: { },
  props: {
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const confirmPass = (rule, value, callback) => {
      if (this.form.busMainData.password !== value) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      dialog: false,
      style: 'width: 184px',
      cpyCode: '',
      cpyName: '',
      timeout: null,
      form: {
        busMainData: {
          id: '',
          userName: '',
          userAccount: '',
          smsVerifyCode: '',
          password: '',
          confirmPassword: '',
          phone: '',
          email: '',
          avatar: '',
          cpyCode: '',
          orgCode: '',
          thirdAccount: '',
          userStatus: 'LOCK',
          enableFlag: 'Y',
          cpyVOS: []
        }
      },
      rules: {
        'busMainData.userName': [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        'busMainData.userAccount': [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 4, max: 50, message: '长度在 4 到 10 个字符', trigger: 'blur' }
        ],
        'busMainData.password': [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 50, message: '长度在 4 到 10 个字符', trigger: 'blur' }
        ],
        'busMainData.confirmPassword': [
          { required: true, validator: confirmPass, trigger: 'blur' }
        ],
        'busMainData.phone': [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        'busMainData.email': [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    isvalidPhone(str) {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      return reg.test(str)
    },
    initDataOfBefore() {
      // this.getAllCpy()
    },
    doSubmit() {
      // 增加校验密码是否相等
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          const _this = this
          _this.form.busMainData.cpyVOS = []
          if (_this.cpyCode) {
            const tmpVO = { cpyCode: _this.cpyCode }
            _this.form.busMainData.cpyVOS.push(tmpVO)
          }
          this.doAdd()
        }
      })
    },
    doAdd() {
      const userAccount = this.form.busMainData.userAccount.toLowerCase()
      const password = md5(this.form.busMainData.password + userAccount)
      const confirmPassword = md5(this.form.busMainData.confirmPassword + userAccount)
      const postData = JSON.parse(JSON.stringify(this.form))
      postData.busMainData.userAccount = userAccount
      postData.busMainData.password = password
      postData.busMainData.confirmPassword = confirmPassword
      userRegister(postData).then(res => {
        this.resetForm()
        this.$notify({
          title: '注册成功.',
          message: userAccount + '欢迎使用.',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.resetForm()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
    },
    cpySearchAsync(cpyName, callback) {
      let results = []
      clearTimeout(this.timeout)
      if (cpyName) {
        getAllCpy(cpyName).then(res => {
          results = res.data
          this.timeout = setTimeout(() => {
            callback(results)
          }, 2000 * Math.random())
        })
      }
    },
    handleCpySelect(item) {
      this.cpyCode = item.cpyCode
      console.log(item)
    }
  }
}
</script>
